<?php


class Model_Base extends Zend_Db_Table {
   
   private $_data;
   protected $_pk = '';
   protected $_fields = array();
   protected $_table = '';
   protected $_name;
   private $_query;
   
   
   
   public function __set($name, $value) {
      if(in_array($name, $this->_fields)) {
         $this->_data[$name] = $value;
      }
   }
   
   public function __get($name) {
      if(in_array($name, $this->_fields)) {
         return $this->_data[$name];
      }
   }
   
   public function __call($name, $arguments) {
      
      if(strstr($name, 'set') || strstr($name, 'get')) {
         preg_match('/(set)(\w+)|(get)(\w+)/', $name, $m);
         foreach($m as $k => &$v) {
            if(strlen(trim($v)) > 0) {
               $m2[] = $v;
            }
         }
         $field = strtolower($m2[2]);
         if(in_array($field, $this->_fields)) {
            if($m2[1] == 'set') {
               $this->_data[$field] = $arguments[0];
            } else if($m2[1] == 'get') {
               return $this->_data[$field];
            } else {
               
            }
         }
      }
   }
   
   /**
    * Static calling
    * Needs PHP 5.3
    *
    * @param string $name
    * @param array $arguments
    */
   public static function __callStatic($name, $arguments) {
      
   }
   
   public function bind($row) {
      foreach($row as $field => $value) {
         call_user_method('set'.ucfirst($field), $this, $value);
      }
   }
   
   public function insert() {
      $db = Zend_Registry::get('db');
      $data = $this->_data;
      unset($data[$this->_pk]);
      $db->insert($this->_name, $data);
   }
   
   public function update() {
      $db = Zend_Registry::get('db');
      $data = $this->_data;
      unset($data[$this->_pk]);
      $db->update($this->_name, $data, sprintf("%s = %s", $this->_pk, $this->getId()));
   }
   
   public function delete() {
      $db = Zend_Registry::get('db');
      $db->delete($this->_name, sprintf("%s = %s", $this->_pk, $this->getId()));
   }
   
   public function getQuery() {
      return $this->_query;
   }
   
//   public function find
   
   public function findBy($field, $value=null, $whereType='AND', $firstOnly=false) {
      $db = Zend_Registry::get('db');
      $where = "";
      if(is_array($field)) {
         foreach($field as $f => $v) {
            if(is_object($v) && get_class($v) == 'Zend_Db_Expr') {
               // :^) ... do nothing
            } else {
               $v = "LIKE '$v'";
            }
            $where .= "$f $v $whereType ";
         }
         $where = preg_replace('/\sAND\s$/', '', $where);
      } else {
         $where = "$field LIKE '$value'";
      }
      $sql = sprintf("
         SELECT 
            %s 
         FROM 
            %s 
         WHERE 
            %s
         ", implode(',', $this->_fields), (isset($this->_name) ? $this->_name :$this->_table), $where
      );
      $this->_query = $sql;
      $rows = $db->fetchAll($sql);
      if(!$rows) {
         return null;
      }
      $arr = array();
      foreach($rows as $row) {
         $cls = get_class($this);
         $obj = new $cls();
         $obj->bind($row);
         $arr[] = $obj;
      }
      if($firstOnly) {
         return $arr[0];
      }
      return $arr;
   }
   
   public function findOneBy($field, $value=null, $whereType='AND', $firstOnly=false) {
      return $this->findBy($field, $value, $whereType, true);
   }
   
   
   public function __toString() {
      $str = "";
      foreach($this->_fields as $key) {
         $str .= $key . ": " . call_user_method('get'.ucfirst($key), $this) . "<br />";
      }
      return $str;
   }
   
   public function getFields() {
      return $this->_fields;
   }
   
   public function getName() {
      return $this->_name;
   }
   
   function getList($textField='name', $valueField='_pk', $beginOptions=array(), $endOptions=array(), $cond=array()) {
      if($valueField == '_pk') {
         $valueField = $this->_pk;
      }
//      $_valueField = $this->$valueField;
      $_valueField = $valueField;
      $_textField = $textField;
      
      $where = '';
      if(is_array($cond)) {
         $where .= 'WHERE'.PHP_EOL;
         foreach ($cond as $k => $v) {
            $where .= sprintf('%s = %s', $k, $v);
         }
      }
      
      $db = Zend_Registry::get('db');
      $sql = sprintf("
         SELECT 
            %s
         FROM 
            %s
         %s
      ", implode(',', $this->getFields()), $this->getName(), $where);
      $rows = $db->fetchAll($sql);
      if(!$rows) {
         return null;
      }
      $arr = array();
      if(count($beginOptions)) {
         $arr = $beginOptions;
      }
      foreach($rows as $row) {
         $arr[$row[$_valueField]] = $row[$_textField];
      }
      if(count($endOptions)) {
         foreach($endOptions as $k => $v) {
            $arr[$k] = $v;
         }
      }
      return $arr;
      
   }
   
   
   
   
}